package com.example;

import org.junit.Test;

import java.lang.reflect.Method;
import java.util.Date;

public class ReflectionMethodDemo {

    // 反射：public void m1()
    @Test
    public void test1() throws Exception {
        Class<Person> personClass = Person.class;
        Person person = personClass.newInstance();
        Method m1 = personClass.getMethod("m1", null);
        // 调用方法
        m1.invoke(person, null);
    }

    // 反射：public void m2(String name)
    @Test
    public void test2() throws Exception {
        Class<Person> personClass = Person.class;
        Person person = personClass.newInstance();
        Method m2 = personClass.getMethod("m2", String.class);
        // 调用方法
        m2.invoke(person, "jack");
    }

    // 反射：public String m3(String name, int age)
    @Test
    public void test3() throws Exception {
        Class<Person> personClass = Person.class;
        Person person = personClass.newInstance();
        Method m3 = personClass.getMethod("m3", String.class, int.class);
        // 调用方法
        m3.invoke(person, "jack", 35);
    }

    // 反射：private void m4(Date date)
    @Test
    public void test4() throws Exception {
        Class<Person> personClass = Person.class;
        Person person = personClass.newInstance();
        Method m4 = personClass.getDeclaredMethod("m4", Date.class);
        m4.setAccessible(true);
        // 调用方法
        m4.invoke(person, new Date());
    }

    // 反射：public static void m5()
    @Test
    public void test5() throws Exception {
        Class<Person> personClass = Person.class;
        Method m5 = personClass.getMethod("m5", null);
        // 调用方法
        m5.invoke(null, null);
    }

    // 反射：private static void m6(String[] args)
    @Test
    public void test6() throws Exception {
        Class<Person> personClass = Person.class;
        Method m6 = personClass.getDeclaredMethod("m6", String[].class);
        m6.setAccessible(true);
        // 调用方法
        // 以下代码运行报错：wrong number of arguments
//        m6.invoke(null, new String[]{"aa","bb"});
        // 使用以下解决
        m6.invoke(null, (Object) new String[]{"aa", "bb"});
        m6.invoke(null, new Object[]{new String[]{"aa", "bb"}});
    }

}
